package serie01.model;

import serie01.util.Currency;

public class StdMultiConverter implements MultiConverter {
	
	// ATTRIBUTS
	
	private Currency[] tabCurrency;
	private double euroAmount;
	
	// CONSTRUCTEUR
	
	public StdMultiConverter(int n) {
		if (n < 2) {
			throw new IllegalArgumentException(
					"Il faut au moins 2 devises"
			);
		}
		euroAmount = 0;
		tabCurrency = new Currency[n];
		for (int i = 0; i < n; i++) {
			tabCurrency[i] = Currency.EUR;
		}
	}
	
	// REQUETES
	
	public double getAmount(int index) {
		if (index < 0 || index >= getCurrencyNb()) {
			throw new IllegalArgumentException(
					"L'index : " + index + " n'existe pas"
			);
		}
		return euroAmount * (tabCurrency[index].getExchangeRate());
	}
	
	public Currency getCurrency(int index) {
		if (index < 0 || index >= getCurrencyNb()) {
			throw new IllegalArgumentException(
					"L'index : " + index + " n'existe pas"
			);
		}
		return tabCurrency[index];
	}
	
	public int getCurrencyNb() {
		return tabCurrency.length;
	}
	
	public double getExchangeRate(int index1, int index2) {
		if (index1 < 0 || index1 >= getCurrencyNb()) {
			throw new IllegalArgumentException(
					"L'index : " + index1 + " n'existe pas"
			);
		}
		if (index2 < 0 || index2 >= getCurrencyNb()) {
			throw new IllegalArgumentException(
					"L'index : " + index2 + " n'existe pas"
			);
		}
		double rate1 = tabCurrency[index1].getExchangeRate();
		double rate2 = tabCurrency[index2].getExchangeRate();
		return rate2 / rate1;
	}
	// COMMANDES
	
	public void setAmount(int index, double amount) {
		if (index < 0 || index >= getCurrencyNb()) {
			throw new IllegalArgumentException(
					"L'index : " + index + " n'existe pas"
			);
		}
		if (amount < 0.0) {
			throw new IllegalArgumentException(
					"Le montant amount doit etre positif, ici amount = "
					+ amount
			);
		}
		euroAmount = tabCurrency[index].getExchangeRate() * amount;		
	}
	
	public void setCurrency(int index, Currency c) {
		if (index < 0 || index >= getCurrencyNb()) {
			throw new IllegalArgumentException(
					"L'index : " + index + " n'existe pas"
			);
		}
		if (c == null) {
			throw new IllegalArgumentException("La devise est null");
		}
		tabCurrency[index] = c;		
	}
	
	public void setEuroExchangeRate(Currency c, double rate) {
		if (c == null) {
			throw new IllegalArgumentException("La devise est null");
		}
		if (rate <= 0.0) {
			throw new IllegalArgumentException(
					"Le taux de change doit etre positif, ici rate = " + rate
			);
		}
		c.setExchangeRate(rate);
	}
}
